/*
 * =====================================================================================
 *
 *       Filename:  main.cc
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2013年07月04日 15时37分25秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Xie Yanping (), 
 *        Company:  www.Qihoo.net
 *
 * =====================================================================================
 */

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "database/simple_db_pool.h"
#include "database/scoped_connection.h"
#include "base/config_reader.h"
#include "im/adapters/message_exchange_adapter.h"

int main(int argc, char **argv) {
  char * conf_file = "./broadcast_message.conf";
  char opt;
  while ((opt = getopt(argc, argv, "c:")) != -1) {
    switch (opt) {
    case 'c':
      conf_file = optarg;
      break;
    default:
      std::cerr << "Unknown option " << optopt << std::endl;
      return 1;
    }
  }

  ConfigReader cfg(conf_file);
  if (!cfg) {
    std::cerr << "Config file " << conf_file << " read error!" << std::endl;
    return 1;
  }

  LOG_INIT(cfg.Get("log4cplus", "file"), cfg.Get("log4cplus", "level"));
  // FcgiServer * fcgi_server = new FcgiServer("127.0.0.1:19000", 128);
  /*
   * 360同城帮上线新功能：
   * 1、商品发布支持上传商品图片及描述
   * 2、商品支持选择上门维修或到店维修
   * 如有意见或者建议请拨打客服电话：400-815-8360。
   */
 /* std::string body="360同城帮上线新功能：\r\n"
    "1、商品发布支持上传商品图片及描述\r\n"
    "2、商品支持选择上门维修或到店维修\r\n"
    "如有建议请拨打客服电话：400-815-8360\r\n";*/
  std::string body = "【360同城帮】尊敬的商家您好，为了让更多的消费者更方便购买您的维修服务，360即将推出“当面付款功能”：所有消费者在选择购买您商品时，可以选择“当面付款、线下交易”的方式完成交易。";
  std::string receiver_list = cfg.Get("message", "receiver_list");
  if (receiver_list.empty()) {
    std::vector<int64_t> id_arr;
    LOG_INFO("id_arr.size = " << id_arr.size() << "receiver list = " << receiver_list);
    base::SimpleConnectionPool  conn_pool(cfg.Get("database", "name").c_str(), cfg.Get("database", "server_list").c_str(),
        cfg.Get("database", "user").c_str(), cfg.Get("database", "password").c_str());
    mysqlpp::ScopedConnection scoped_conn(conn_pool);
    if (!scoped_conn) {
      LOG_ERROR("insert message error.(DB connect error.)");
      return -1;
    }

    mysqlpp::Query query(scoped_conn->query());
    query << "SELECT qid from shop_base";
    try {
      mysqlpp::UseQueryResult ret = query.use();
      if (ret) {
        while (mysqlpp::Row row = ret.fetch_row()) {
          id_arr.push_back(row["qid"]);
        }
        LOG_INFO("id_arr.size = " << id_arr.size());
        std::string sender=cfg.Get("message", "sender");
        BOOST_FOREACH(const int64_t qid, id_arr) {
          imserver::ImMessage message;
          try {
            message.__set_sender(boost::lexical_cast<int64_t>(sender));
          } catch (...) {}
          message.__set_receiver(qid);
          message.__set_body(body);
          message.__set_seq_id(0);
          message.__set_flags(0);
          message.__set_timestamp(time(NULL));
          imserver::MessageExchangeAdapter::Instance().CreateMessage(message, 2);
          usleep(200000);
        }
      }
    } catch (mysqlpp::Exception& e) {
      LOG_ERROR(query.str() << " exec ERROR.(" << e.what() << ")");
      return -1;
    }
  } else {
    std::vector<std::string> id_arr;
    boost::split(id_arr, receiver_list, boost::is_any_of("&|"));
    LOG_INFO("id_arr.size = " << id_arr.size());
    std::string sender=cfg.Get("message", "sender");
    BOOST_FOREACH(const std::string& qid, id_arr) {
      imserver::ImMessage message;
      try {
        message.__set_sender(boost::lexical_cast<int64_t>(sender));
        message.__set_receiver(boost::lexical_cast<int64_t>(qid));
      } catch (...) {}
      message.__set_body(body);
      message.__set_seq_id(0);
      message.__set_flags(0);
      message.__set_timestamp(time(NULL));
      imserver::MessageExchangeAdapter::Instance().CreateMessage(message, 2);
      usleep(200000);
    }
  }


  return 0;
}

